#!python
"""
reloadall.py: transitively reload nested modules (2.X + 3.X).
Call reload_all with one or more imported module objects.
"""

from cProfile import label
import types
from importlib import reload
from decotools import timer


def status(module):
    print('reloading ' + module.__name__)


def tryreload(module):
    try:
        reload(module)
    except Exception as ex:
        print('FAILED %s, Exceptoin: %s' % (module, ex))


def transitive_reload(module, visited):
    if not module in visited:
        status(module)
        tryreload(module)
        visited[module] = True
        for attrobj in module.__dict__.values():
            if type(attrobj) == types.ModuleType:
                transitive_reload(attrobj, visited)


@timer(label='###')
def reload_all(*args):
    visited = {}
    for arg in args:
        if type(arg) == types.ModuleType:
            transitive_reload(arg, visited)


if __name__ == '__main__':
    import importlib
    import sys
    if len(sys.argv) > 1:
        modulename = sys.argv[1]
    else:
        modulename = 'reloadall'
    module = importlib.import_module(modulename)
    reload_all(module)
